const Koa = require('koa')
const Router = require('koa-router')
const Mont = require('monk')
const koaBody = require('koa-body')
// 创建Koa对象
const app = new Koa();
const router = new Router();
app.use(koaBody())

// 链接数据库
let db = new Mont('localhost:27017/admin');

// 获取表
let Article = db.get('article');
let Tags = db.get('tags');

/**
 * 数据库新增一条文章信息
 * @param data
 * @returns {Promise<*>}
 */
async function createArticle(data){
    return await Article.insert({
        title: data.title,
        content: data.content,
        tagType: data.tagType,
        date: data.date,
        hot: 0
    })
}


/**
 * 查询数据库文章详情
 * @param _id
 * @returns {Promise<*>}
 */
async function getArticleDetail(_id){
    return await Article.find({
        _id
    })
}

/**
 * 查询标签
 */
async function getTags(){
    return await Tags.find();
}

/**
 * 更新标签
 * @param updatas
 */
async function updateTags(updatas){
    const data = await getTags();
    return await Tags.update({'tags': data[0].tags}, {'tags': updatas})
}

/**
 * 创建文章
 * @param ctx
 */ 

async function create(ctx){
    // 收到客户端传来参数
    let req = ctx.request.body;    
    let {body} = JSON.parse(req.data);
    if(body.title && body.content && body.tagType) {
        try{
            let tagName = ['0','less', '前端', 'JAVASRICT', '后端', 'Flex', '其他'];
            const ret = await createArticle(body);
            const data = await getArticleDetail(ret._id);
            const getTagsData = await getTags();
            const upTags = getTagsData[0].tags.concat(new Array(tagName[body.tagType]));
            const TagsData = await updateTags(Array.from(new Set(upTags)));        
            ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg: '创建文章成功',
                data
            }
        }catch(err){
            ctx.response.status = 412;
            ctx.body = {
                code: 412,
                msg: '创建文章失败',
                data: err
            }
        }
    }else{
        ctx.response.status = 416;
        ctx.body = {
            code: 200,
            mes: '参数不正确'
        }
    }
}

/**
 * 文章详情
 * @param ctx
 */ 

async function detail(ctx){
    // 接受客户端
    let req = ctx.request.body;
    let data = '';
    for(let key in req) {
        data = JSON.parse(key);
    }
    let {body} = JSON.parse(data.data);
    if(body.id) {
        try{
            const data = await getArticleDetail(body.id);
            Article.update({"_id": body.id},{$set:{"hot": data[0].hot+=1}})
            ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg: '查询成功',
                data
            }
        }catch(err){
            ctx.response.status = 412;
            ctx.body = {
                code: 412,
                msg: '查询失败',
                data: err
            }
        }
    }else{
        ctx.response.status = 416;
        ctx.body = {
            code: 200,
            mes: 'ID必须传'
        }
    }
}


// 创建路由
// 文章搜索
router.get('/captcha', async (ctx)=>{
    let req = await Article.find({}, {sort: {'date': -1}});
    let getTg = await Tags.find();
    ctx.body = {
        code: 200,
        docs: req,
        tags: getTg,
        meg: '请求成功'
    }
});

// 标签搜索
router.get('/captcha/:tagType', async (ctx)=>{
    let req = await Article.find({'tagType': ctx.params.tagType}, {sort: {'date': -1}});
    ctx.body = {
        code: 200,
        docs: req,
        meg: '请求成功'
    }
});

// 热门文章
router.get('/hot', async (ctx)=>{
    let req = await Article.find({}, {sort: {'hot': -1}});
    ctx.body = {
        code: 200,
        docs: req,
        meg: '请求成功'
    }
});

// 创建文章，文章详情
router.post('/article', create);
router.post('/detail', detail);

// 加载路由中间件
app.use(router.routes());
app.use(router.allowedMethods());

// 在端口3000监听:
app.listen(3000, () => {
    console.log('listening on port 3000')
})
